#import <stdlib.h>
#import <Ice/Ice.h>
#import "eventConsumer.h"

@implementation EventConsumer

-(id) initWithCommunicator:(id<ICECommunicator>)communicator andHost:(NSString*)host
{
	if (![super init])
		return nil;
		
	comm = communicator;
	
	[self createConsumer:host];
	
	return self;
}

-(void) dealloc
{
	//[topic unsubscribe:subscriber];
	id<ICEInputStream> is = nil;
	id<ICEOutputStream> os = [topic createOutputStream__];
	[os writeProxy:subscriber];
	
	[topic invoke__:@"unsubscribe" mode:ICENormal os:os is:&is context:[topic ice_getContext]];
	
	[topic release];
	[subscriber release];
	
	[super dealloc];
}

-(void) createConsumer:(NSString*)host
{
	NSString* aux = [NSString stringWithFormat:@"DemoIceStorm/TopicManager:tcp -h %@ -p 10000", host];
	id<ICEObjectPrx> manager = [comm stringToProxy:aux];
    if(!manager)
    {
		@throw [NSException exceptionWithName:@"InvalidProxyException" reason:@"Invalid consumer proxy" userInfo:nil];
    }

    @try
    {
        //topic = manager->retrieve("events");
		id<ICEInputStream> is = nil;
		id<ICEOutputStream> os = [manager createOutputStream__];
		[os writeString:@"events"];
		
		[manager invoke__:@"retrieve" mode:ICEIdempotent os:os is:&is context:[manager ice_getContext]];
		
		topic = [[ICEObjectPrx ice_readWithStream:is] retain];
    }
    @catch(ICEException* e)
    {
        @try
        {
			//topic = manager->create("events");
			id<ICEInputStream> is = nil;
			id<ICEOutputStream> os = [manager createOutputStream__];
			[os writeString:@"events"];
			
			[manager invoke__:@"create" mode:ICENormal os:os is:&is context:[manager ice_getContext]];
			
			topic = [[ICEObjectPrx ice_readWithStream:is] retain];
        }
        @catch(ICEException* e2)
        {
			@throw [NSException exceptionWithName:@"ConnectionFailureException" reason:@"Temporary failure. try again." userInfo:nil];
        }
    }

    id<ICEObjectAdapter> adapter = [comm createObjectAdapterWithEndpoints:@"MIDataAccessor.Subscriber" endpoints:@"default"];
	
    subscriber = [adapter add:self identity:[comm stringToIdentity:[ICEUtil generateUUID]]];

    @try
    {	
        //topic->subscribeAndGetPublisher(qos, subscriber);
		NSDictionary* qos = [[NSDictionary alloc] init];
		
		id<ICEInputStream> is = nil;
		id<ICEOutputStream> os = [topic createOutputStream__];
		
		ICEKeyValueTypeHelper helper;
		helper.key = [NSString class];
		helper.value = [NSString class];
		[os writeDictionary:qos type:helper];
		[os writeProxy:subscriber];
		
		[topic invoke__:@"subscribeAndGetPublisher" mode:ICENormal os:os is:&is context:[topic ice_getContext]];
		
		[qos release];
    }
    @catch(ICEException* e)
    {
		@throw [NSException exceptionWithName:@"SubscriptionException" reason:@"Error subscribing." userInfo:nil];
    }
   
	[adapter activate];
}

-(void) push:(CollaborationMutableEvent *)evt current:(ICECurrent *)current
{
	//NO SE IMPLEMENTA
}

@end
